package com.md.base;

import com.md.base.exception.ErrorMessage;
import com.md.base.exception.ServerException;
import com.md.model.system.CommonResult;
import com.md.value.enums.ErrorEnum;
import org.springframework.core.Ordered;
import org.springframework.http.MediaType;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

public abstract class BaseFilter extends OncePerRequestFilter implements Ordered {
  /**
   * 值越低优先级越高
   */
  private final Integer priority;

  public BaseFilter(final Integer priority) {
    this.priority = priority;
  }

  public void errorEnum(final HttpServletResponse response,
                        final EnumBase errorEnum) throws IOException {
    response.setCharacterEncoding(StandardCharsets.UTF_8.name());
    response.setContentType(MediaType.APPLICATION_JSON_VALUE);
    response.getWriter().println(CommonResult.error(errorEnum));
    response.setStatus(errorEnum.getCode());
    response.getWriter().flush();
  }

  public void errorEnum(final HttpServletResponse response,
                        final Exception e) throws IOException {
    if (e instanceof ServerException) {
      ServerException serverException = (ServerException) e;
      errorEnum(response, ErrorMessage.of(serverException.getCode(), serverException.getMessage()));
      return;
    }
    errorEnum(response, ErrorMessage.of(ErrorEnum.SYSTEM_ERROR.getCode(), e.getMessage()));
  }

  @Override
  public int getOrder() {
    return priority;
  }
}
